<template>
  <view class="content">
    <gui-xhs-header-leading
      style="position: absolute; top: 40rpx; left: 10rpx; z-index: 20"
      :backButtonClass="['gui-color-white']"
      :home="false"
      @goBack="goBack"
    >
    </gui-xhs-header-leading>

    <!-- 右上角分享按钮 -->
    <view class="top-right-share" @click.stop="share()">
      <image
        class="share-icon"
        src="/static/image/fx.png"
        mode="aspectFit"
      ></image>
    </view>

    <view
      class="video-container"
      @click="togglePlayPause"
      v-if="video && video.videoUrl"
    >
      <video
        class="video"
        :src="video.videoUrl"
        :poster="video.firstPicture"
        id="video_player"
        :loop="true"
        :controls="false"
        :show-center-play-btn="false"
        :show-play-btn="false"
        :muted="isMuted"
        object-fit="contain"
        @timeupdate="handleTimeUpdate"
      ></video>

      <text v-if="paused" class="play-icon">▶</text>

      <!-- Right Action Bar -->
      <view class="right-actions">
        <view class="action-item avatar-container">
          <image
            class="user-avatar"
            :src="video.authorAvatar"
            @tap.stop="goCard(video)"
            mode="aspectFill"
          ></image>
          <!-- 关注按钮 - 移动到头像下方居中 -->
          <view
            v-if="video.authorId != userId && !author.isFollow"
            class="follow-btn-center"
            @click.stop="toggleFollow"
          >
            <image
              class="follow-btn-img-center"
              src="/static/my/bianjiIcon@3x.png"
            ></image>
          </view>
        </view>
        <view class="action-item" @click.stop="upNote(video)">
          <image
            class="icon"
            :src="video.isUp ? filledHeartIcon : outlineHeartIcon"
          ></image>
          <text class="action-text">{{ video.upCount }}</text>
        </view>
        <view class="action-item" @click.stop="handleComment(video)">
          <image class="icon" :src="commentIcon"></image>
          <text class="action-text">{{ video.replyCount || 0 }}</text>
        </view>
        <view class="action-item" @click.stop="starNote(video)">
          <image
            class="icon"
            :src="video.isStar ? filledStarIcon : outlineStarIcon"
          ></image>
          <text class="action-text">{{ video.starCount }}</text>
        </view>
        <view class="action-item" @click.stop="rewardOperate">
          <image
            class="icon"
            src="/static/image/dsfff.png"
            mode="aspectFit"
          ></image>
          <text class="action-text">打赏</text>
        </view>
      </view>

      <!-- Bottom Info -->
      <view class="bottom-info">
        <text class="author">@{{ video.authorName }}</text>
        <view class="video-description">
          <text class="video-title" v-if="video.noteTitle">{{
            video.noteTitle
          }}</text>
          <text class="video-content">{{ video.noteContent }}</text>
        </view>
        <text class="video-time"
          >{{ formatDate(video.createTime) }} {{ video.ipRealAddress }}</text
        >
      </view>

      <!-- Progress Bar -->
      <view class="progress-bar-container" v-if="currentVideoDuration > 0">
        <slider
          class="progress-slider"
          :value="currentVideoProgress"
          :max="currentVideoDuration"
          @change="handleSliderChange"
          @changing="handleSliderChanging"
          block-size="14"
          activeColor="#FFFFFF"
          backgroundColor="rgba(255, 255, 255, 0.4)"
        />
        <!-- 声音控制按钮 -->
        <view class="sound-control" @click.stop="toggleSound">
          <image
            class="sound-icon"
            :src="isMuted ? mutedSoundIcon : soundIcon"
          ></image>
        </view>
        <text class="time-display"
          >{{ formatTime(currentVideoProgress) }} /
          {{ formatTime(currentVideoDuration) }}</text
        >
      </view>
    </view>

    <!-- 无内容提示 -->
    <view class="no-more-videos" v-if="!video && !loading">
      <text class="no-more-icon">🎬</text>
      <text class="no-more-text">暂无视频内容</text>
    </view>

    <!-- 加载提示 -->
    <view class="loading-indicator" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 评论弹窗 -->
    <comment-modal
      :visible="showCommentModal"
      :comments="activeComments"
      :authorId="video && video.authorId"
      @close="showCommentModal = false"
      @send="handleSendComment"
      @like="upReply"
    />
    <!-- 收藏夹弹窗 -->
    <uni-popup ref="popup" type="center" border-radius="10px 10px 0 0">
      <view class="list">
        <view class="tit"> 请选择收藏夹</view>
        <scroll-view
          style="height: 460rpx"
          @scrolltolower="scM"
          scroll-y="true"
          class="scroll-Y"
        >
          <view
            class="list-msg"
            v-for="(item, index) in scList"
            @click="scSubmit(item)"
          >
            {{ item.folderTitle }}收藏夹
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 遮罩层 -->
    <view class="mask" v-if="isRewardPopupVisible" @click="closePopup"></view>

    <!-- 打赏弹窗 -->
    <view class="popup" v-if="isRewardPopupVisible">
      <view class="popup-content">
        <view class="popupTop">
          <view class="popupBtn"> </view>
          <view class="popupText"> 打赏 </view>
        </view>
        <view class="popupContent">
          <view
            class="popupContentItem"
            @click="openPayPopup(item)"
            v-for="(item, index) in giftsList"
            :key="index"
          >
            <image src="/static/main/dashang1@2x.png" mode="aspectFit"></image>
            <text>￥{{ item.giftPrice }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 支付方式选择弹窗 -->
    <PaySelectPopup
      :show="isPayPopupVisible"
      :defaultMethod="selectedPayMethod"
      @close="closePayPopup"
      @confirm="onPayMethodConfirm"
    />
  </view>
</template>

<script>
import CommentModal from "../../../components/CommentModal.vue";
import PaySelectPopup from "@/components/PaySelectPopup.vue";
import commonMixin from "@/mixin/commonMinxin";

export default {
  mixins: [commonMixin],
  components: {
    CommentModal,
    PaySelectPopup,
  },
  data() {
    const filledHeartSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#fe2c55"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"></path></svg>`;
    const outlineHeartSvg = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="white"><path stroke-linecap="round" stroke-linejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" /></svg>`;
    const commentSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"></path></svg>`;
    const filledStarSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#F7BD5C"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"></path></svg>`;
    const outlineStarSvg = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="white"><path stroke-linecap="round" stroke-linejoin="round" d="M11.48 3.499a.562.562 0 011.04 0l2.125 5.111a.563.563 0 00.475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 00-.182.557l1.285 5.385a.562.562 0 01-.84.61l-4.725-2.885a.563.563 0 00-.586 0L6.982 20.54a.562.562 0 01-.84-.61l1.285-5.386a.562.562 0 00-.182-.557l-4.204-3.602a.563.563 0 01.321-.988l5.518-.442a.563.563 0 00.475-.345L11.48 3.5z" /></svg>`;
    const soundSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"></path></svg>`;
    const mutedSoundSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"></path></svg>`;

    return {
      // --- 视频数据与状态 ---
      video: {}, // 单个视频数据
      videoContext: null, // 视频上下文对象，用于控制播放、暂停等
      paused: false, // 当前视频是否处于暂停状态
      currentVideoProgress: 0, // 当前视频的播放进度，单位：秒
      currentVideoDuration: 0, // 当前视频的总时长，单位：秒
      isSeeking: false, // 标记用户是否正在拖动进度条，防止与timeupdate事件冲突
      isMuted: true, // 是否静音
      showSuccessMask: false, // 关注成功提示

      // --- 评论相关 ---
      showCommentModal: false, // 是否显示评论弹窗
      activeComments: {
        // 当前活动的评论区数据
        noteId: "", // 评论所属的笔记ID
        count: 0, // 评论总数
        list: [], // 评论列表
      },
      loadedReplies: {}, // 记录已加载过评论的视频ID，避免重复请求，格式: { noteId: true }

      // --- UI 图标 ---
      filledHeartIcon:
        "data:image/svg+xml;charset=utf-8," +
        encodeURIComponent(filledHeartSvg), // 实心点赞图标
      outlineHeartIcon:
        "data:image/svg+xml;charset=utf-8," +
        encodeURIComponent(outlineHeartSvg), // 空心点赞图标
      commentIcon:
        "data:image/svg+xml;charset=utf-8," + encodeURIComponent(commentSvg), // 评论图标
      filledStarIcon:
        "data:image/svg+xml;charset=utf-8," + encodeURIComponent(filledStarSvg), // 实心收藏图标
      outlineStarIcon:
        "data:image/svg+xml;charset=utf-8," +
        encodeURIComponent(outlineStarSvg), // 空心收藏图标
      soundIcon:
        "data:image/svg+xml;charset=utf-8," + encodeURIComponent(soundSvg), // 声音开图标
      mutedSoundIcon:
        "data:image/svg+xml;charset=utf-8," + encodeURIComponent(mutedSoundSvg), // 声音关图标

      // --- 加载控制 ---
      loading: false, // 是否正在加载数据（防止重复请求）

      // --- 用户与性能优化 ---
      user: uni.app.getStorage("user"), // 当前登录的用户信息

      // --- 新增字段 ---
      noteId: "", // 当前笔记ID
      note: {}, // 笔记详情
      author: {}, // 作者信息

      // --- 收藏相关 ---
      starNoteData: {}, // 收藏笔记数据
      offset: 1, // 收藏夹分页
      scList: [
        // 收藏夹列表
        {
          folderTitle: "普通",
          starFolderId: null,
        },
      ],
      userId: uni.getStorageSync("userId"),

      // 打赏相关数据
      isRewardPopupVisible: false,
      giftsList: [],
      isPayPopupVisible: false,
      orderItem: null,
      selectedPayMethod: "1",
      payMethods: [
        { label: "支付宝", value: "1" },
        { label: "微信支付", value: "2" },
        { label: "余额支付", value: "4" },
      ],
    };
  },
  onLoad(options) {
    console.log(options);
    // let checkLogin = uni.app.checkLogin();
    // if (checkLogin) {
    //   // 如果有指定noteId，则加载该笔记
    if (options.noteId) {
      this.noteId = options.noteId;
      // 加载视频和笔记详情
      this.loadNoteData(options.noteId);
    } else {
      uni.showToast({ title: "未指定视频", icon: "none" });
      setTimeout(() => uni.navigateBack(), 1000);
    }
    // }

    // 初始化收藏夹列表
    this.scInit();
  },
  onReady() {
    this.initVideoContext();
  },
  methods: {
    goBack() {
      uni.navigateBack({ delta: 1 });
      // 添加原生应用回调
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          if (window.AndroidBridge && window.AndroidBridge.backEvent) {
            window.AndroidBridge.backEvent();
            console.log("调用Android返回事件");
          }
          break;
        case "ios":
          if (
            window.webkit &&
            window.webkit.messageHandlers &&
            window.webkit.messageHandlers.backEvent
          ) {
            window.webkit.messageHandlers.backEvent.postMessage({});
            console.log("调用iOS返回事件");
          }
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },

    initVideoContext() {
      this.videoContext = uni.createVideoContext("video_player", this);
      setTimeout(() => {
        if (this.videoContext) {
          try {
            // 判断平台
            const platform = uni.getSystemInfoSync().platform;
            if (platform === "android" || platform === "ios") {
              // APP端尝试直接有声播放
              this.isMuted = true; // 默认先静音
            } else {
              // H5端先静音自动播放
              this.isMuted = true;
            }
            this.videoContext.play();
            this.paused = false;
            console.log("尝试自动播放视频，平台：", platform);
          } catch (err) {
            console.log("自动播放失败，需要用户交互:", err);
            this.paused = true;
          }
        }
      }, 300);
    },

    // 切换声音状态
    toggleSound(e) {
      e.stopPropagation(); // 阻止事件冒泡
      this.isMuted = !this.isMuted;

      if (this.videoContext) {
        // 更新视频播放器静音状态
        this.videoContext.muted = this.isMuted;
        console.log("声音状态切换为:", this.isMuted ? "静音" : "有声");
      }
    },

    // 关注/取消关注作者
    toggleFollow(e) {
      if (!this.author.isFollow) {
        // 关注作者
        uni.app.post(
          "/blog/action/followAuthor",
          {
            followAuthorId: this.video.authorId,
            authorId: uni.getStorageSync("userId"),
          },
          "json",
          "",
          (res) => {
            if (res.code == 2000) {
              uni.showToast({ title: "关注成功", icon: "none" });
              this.getAuthor();
            }
          },
        );
      } else {
        // 取消关注
        uni.app.post(
          "/blog/action/cancelFollowAuthor",
          {
            followAuthorId: this.video.authorId,
            authorId: uni.getStorageSync("userId"),
          },
          "json",
          "",
          (res) => {
            if (res.code == 2000) {
              // 刷新作者信息
              this.getAuthor();
            }
          },
        );
      }
    },

    loadNoteData(noteId) {
      this.loading = true;
      uni.app.post(
        "/blog/home/getNote",
        {
          noteId: noteId,
          authorId: uni.getStorageSync("userId"),
          keyword: "",
        },
        "json",
        "",
        (noteRes) => {
          console.log(noteRes);
          this.loading = false;

          if (!noteRes || noteRes.code !== 2000 || !noteRes.data) {
            uni.showToast({ title: "视频加载失败, 即将返回", icon: "none" });
            setTimeout(() => uni.navigateBack(), 1500);
            return;
          }

          // 设置视频数据
          this.video = noteRes.data;
          // 设置笔记详情
          this.note = noteRes.data;

          // 获取作者信息
          this.getAuthor();

          // 初始化视频和预加载评论
          this.$nextTick(() => {
            this.initVideoContext();
            this.preloadComments(this.video.noteId);
          });
        },
      );
    },

    preloadComments(noteId, force = false) {
      console.log("开始预加载评论, noteId:", noteId);
      // 避免重复加载同一视频的评论
      if (this.loadedReplies[noteId] && !force) return;

      uni.app.post(
        "/blog/note/getNoteReply",
        {
          noteId: noteId,
          authorId: uni.getStorageSync("userId"),
        },
        "json",
        "",
        (res) => {
          console.log("预加载评论数据:", res);
          if (res.code == 2000 && res.data) {
            // 确保comments是数组
            const replys = Array.isArray(res.data.replys)
              ? res.data.replys
              : [];
            console.log("预加载获取到评论数组:", replys.length, "条");

            // 直接更新全局评论状态
            this.activeComments = {
              noteId: noteId,
              count: res.data.totalCount || 0,
              list: replys,
            };

            // 更新视频数据
            this.video.replys = replys;
            this.video.replyCount = res.data.totalCount || 0;

            // 标记评论已加载
            this.loadedReplies[noteId] = true;

            console.log("预加载完成，当前activeComments:", this.activeComments);
          }
        },
      );
    },

    togglePlayPause() {
      if (!this.videoContext) return;

      this.paused = !this.paused;
      if (this.paused) {
        this.videoContext.pause();
      } else {
        // 用户交互触发播放
        this.videoContext.play();
        // 如果是首次点击播放，可以取消静音
        if (this.videoContext.muted) {
          setTimeout(() => {
            this.videoContext.muted = false;
            console.log("用户交互，取消静音");
          }, 100);
        }
      }
    },

    upNote(video) {
      video.noteId = parseInt(video.noteId);
      let data = {
        authorId: video.authorId,
        authorName: video.authorName,
        followId: uni.getStorageSync("userId"),
        noteId: video.noteId,
        noteTitle: video.noteTitle,
      };
      uni.app.post("/blog/action/upNote", data, "json", "", (res) => {
        if (res.data) {
          // 直接更新UI
          this.video.isUp = true;
          this.video.upCount = (this.video.upCount || 0) + 1;
        } else {
          this.video.isUp = false;
          this.video.upCount = Math.max(0, (this.video.upCount || 1) - 1);
        }

        // 刷新笔记详情状态
        setTimeout(() => this.refreshNoteDetail(), 300);
      });
    },
    getAuthor() {
      uni.app.post(
        "/blog/author/getAuthor",
        {
          authorId: uni.getStorageSync("userId"),
          followAuthorId: this.note.authorId,
        },
        "",
        "",
        (res) => {
          console.log(res);
          this.author = res.data;
        },
      );
    },
    refreshNoteDetail() {
      // 只刷新状态，不做全部重新加载
      console.log("刷新笔记状态:", this.noteId);
      uni.app.post(
        "/blog/home/getNote",
        {
          noteId: this.noteId,
          authorId: uni.getStorageSync("userId"),
          keyword: "",
        },
        "",
        "",
        (res) => {
          if (res && res.data) {
            // 只更新点赞、收藏等状态字段，不影响视频播放
            this.video.isUp = res.data.isUp;
            this.video.isStar = res.data.isStar;
            this.video.upCount = res.data.upCount;
            this.video.starCount = res.data.starCount;
            // 更新笔记详情
            this.note = res.data;
            console.log("笔记状态已刷新");
          }
        },
      );
    },

    // 加载收藏夹列表
    scInit() {
      uni.app.post(
        "/blog/note/getStarFolder",
        {
          authorId: uni.getStorageSync("userId"),
          limit: 10,
          offset: this.offset,
        },
        "",
        "",
        (res) => {
          this.scList = this.scList.concat(res.data.records);
        },
      );
    },

    // 加载更多收藏夹
    scM() {
      console.log("加载更多收藏夹");
      this.offset++;
      this.scInit();
    },

    // 提交收藏
    scSubmit(item) {
      console.log(item.starFolderId, "选择的收藏夹");

      // 根据接口要求构建参数
      let notes = {
        authorId: this.note.authorId, // 笔记作者id
        authorName: this.note.authorName, // 笔记作者名字
        followId: uni.getStorageSync("userId"), // 当前作者id
        noteId: parseInt(this.note.noteId), // 笔记id
        noteTitle: this.note.noteTitle, // 笔记标题
        starFolderId: item.starFolderId, // 收藏夹id
      };

      console.log(notes, "收藏参数");
      uni.app.post("/blog/action/starNote", notes, "json", "", (res) => {
        this.refreshNoteDetail();
        this.$refs.popup.close();
      });
    },

    starNote(video) {
      this.starNoteData = video;

      if (this.video.isStar) {
        // 如果已经收藏，则取消收藏
        let data = {
          authorId: video.authorId,
          followId: uni.getStorageSync("userId"),
          noteId: parseInt(video.noteId),
          noteTitle: video.noteTitle,
        };

        uni.app.post("/blog/action/starNote", data, "json", "", (res) => {
          this.refreshNoteDetail();
        });
      } else {
        // 如果未收藏，则打开收藏夹选择弹窗
        this.$refs.popup.open();
      }
    },

    handleComment(video) {
      console.log("点击查看评论按钮, noteId:", video.noteId);

      // 显示加载中
      uni.showLoading({
        title: "加载评论中...",
      });

      // 获取最新评论数据
      uni.app.post(
        "/blog/note/getNoteReply",
        {
          noteId: video.noteId,
          authorId: uni.getStorageSync("userId"),
        },
        "json",
        "",
        (res) => {
          uni.hideLoading();
          console.log("评论数据获取结果:", res);

          if (res.code == 2000 && res.data) {
            const replys = Array.isArray(res.data.replys)
              ? res.data.replys
              : [];
            console.log("获取到评论数组:", replys.length, "条评论");

            // 检查评论数据结构
            if (replys.length > 0) {
              console.log("第一条评论示例:", JSON.stringify(replys[0]));
            } else {
              console.log("暂无评论");
            }

            // 更新全局状态
            this.activeComments = {
              noteId: video.noteId,
              count: res.data.totalCount || 0,
              list: replys,
            };

            // 更新视频评论数据
            this.video.replys = replys;
            this.video.replyCount = res.data.totalCount || 0;

            // 标记评论已加载
            this.loadedReplies[video.noteId] = true;
          } else {
            // 默认空数据
            this.activeComments = {
              noteId: video.noteId,
              count: 0,
              list: [],
            };
          }

          // 强制触发更新并显示弹窗
          this.$nextTick(() => {
            console.log(
              "准备打开评论弹窗，当前数据:",
              JSON.stringify(this.activeComments),
            );
            // 先确保关闭
            this.showCommentModal = false;

            // 延迟打开，确保DOM更新
            setTimeout(() => {
              this.showCommentModal = true;
              console.log("评论弹窗已打开");
            }, 100);
          });
        },
      );
    },
    // 关闭窗口
    close: function () {
      // 展示底部按钮
      this.buttonShow = true;
    },
    submit: function (e) {
      console.log(e);
      if (uni.app.isEmpty(e.content)) {
        uni.app.msg("请输入评论内容~");
        return;
      }
      const replyData = {
        noteId: e.noteId,
        authorId: uni.getStorageSync("userId"),
        replayContent: e.content,
      };
      if (!uni.app.isEmpty(e.topParentId)) {
        replyData.topParentId = e.topParentId;
      }
      if (!uni.app.isEmpty(e.parentId)) {
        replyData.parentId = e.parentId;
      }
      uni.app.post("/blog/action/replyNote", replyData, "json", "", (res) => {
        console.log(res);
        this.preloadComments(e.noteId, true); // 强制刷新评论
      });
    },

    // 获取评论列表
    getNoteReply(noteId) {
      console.log("获取评论列表:", noteId);
      uni.showLoading({
        title: "刷新评论...",
      });

      uni.app.post(
        "/blog/note/getNoteReply",
        {
          noteId: noteId,
          authorId: uni.getStorageSync("userId"),
        },
        "json",
        "",
        (res) => {
          uni.hideLoading();
          console.log("刷新评论数据:", res);

          if (res.code == 2000 && res.data) {
            // 确保 replys 是数组
            const replys = Array.isArray(res.data.replys)
              ? res.data.replys
              : [];
            console.log("处理后的评论列表:", replys);

            if (replys.length > 0) {
              console.log("第一条评论数据:", JSON.stringify(replys[0]));
            } else {
              console.log("评论列表为空");
            }

            // 更新视频评论数据
            this.video.replys = replys;
            this.video.replyCount = res.data.totalCount || 0;

            // 判断是否是发布评论触发的刷新
            const isCommentRefresh = this.showCommentModal;

            if (isCommentRefresh) {
              // 如果是在评论弹窗打开的状态下刷新，直接更新数据，不关闭弹窗
              // 重新创建一个新对象，确保响应式
              this.activeComments = {
                noteId: noteId,
                count: res.data.totalCount || 0,
                list: replys,
              };

              // 标记已加载
              this.loadedReplies[noteId] = true;
              console.log("评论弹窗已打开状态下更新数据:", this.activeComments);
            } else {
              // 如果是首次打开评论，则正常打开弹窗
              // 重新创建一个新对象，确保响应式
              this.activeComments = {
                noteId: noteId,
                count: res.data.totalCount || 0,
                list: replys,
              };

              // 标记已加载
              this.loadedReplies[noteId] = true;

              // 打开弹窗
              console.log("打开评论弹窗，数据:", this.activeComments);
              this.showCommentModal = true;
            }
          } else {
            uni.showToast({
              title: "获取评论失败",
              icon: "none",
            });
          }
        },
      );
    },
    handleSendComment(commentData) {
      console.log("提交评论:", commentData);

      // 显示加载中
      uni.showLoading({
        title: "提交中...",
      });

      const replyData = {
        authorId: uni.getStorageSync("userId"),
        noteId: this.video.noteId,
        parentId: commentData.replyTo || null,
        replayContent: commentData.content,
        replayImgId: commentData.imageId || "",
        replayImgUrl: commentData.imageUrl || "",
        topParentId: commentData.topParentId || null,
      };

      // 如果是回复评论
      if (commentData.topParentId) {
        replyData.topParentId = commentData.topParentId;
      }

      if (commentData.replyTo) {
        replyData.parentId = commentData.replyTo;
      }

      console.log("发送评论数据:", replyData);

      uni.app.post("/blog/action/replyNote", replyData, "json", "", (res) => {
        console.log("评论提交结果:", res);

        if (res.code == 2000) {
          uni.showToast({
            title: "评论成功",
            icon: "success",
          });

          // 立即获取最新评论列表
          setTimeout(() => {
            this.getNoteReply(this.activeComments.noteId);
          }, 500);
        } else {
          uni.showToast({
            title: "评论失败",
            icon: "none",
          });
        }

        uni.hideLoading();
      });
    },

    upReply(reply) {
      console.log("点赞评论:", reply);
      // 按照API文档构建参数
      let data = {
        followId: uni.getStorageSync("userId"), // 当前用户ID
        replyId: reply.replyId, // 评论ID
        noteId: this.activeComments.noteId, // 笔记ID
        authorId: reply.authorId, // 评论作者ID
        authorName: reply.authorName, // 评论作者名称
        noteTitle: reply.noteTitle || "", // 笔记标题
      };

      console.log("点赞评论请求数据:", data);

      uni.app.post("/blog/action/upReply", data, "json", "", (res) => {
        console.log("点赞评论结果:", res.data);

        // 找到评论在列表中的索引
        const commentIndex = this.activeComments.list.findIndex(
          (item) => item.replyId === reply.replyId,
        );

        if (commentIndex !== -1) {
          // 直接评论
          if (res.data === true) {
            // 使用Vue的$set确保响应式更新
            this.$set(this.activeComments.list[commentIndex], "isUp", true);
            this.$set(
              this.activeComments.list[commentIndex],
              "upCount",
              (reply.upCount || 0) + 1,
            );
          } else {
            this.$set(this.activeComments.list[commentIndex], "isUp", false);
            this.$set(
              this.activeComments.list[commentIndex],
              "upCount",
              Math.max(0, (reply.upCount || 1) - 1),
            );
          }
        } else {
          // 可能是嵌套回复，需要在父评论的回复列表中查找
          let found = false;
          for (let i = 0; i < this.activeComments.list.length; i++) {
            const parentComment = this.activeComments.list[i];
            if (parentComment.reply && Array.isArray(parentComment.reply)) {
              const replyIndex = parentComment.reply.findIndex(
                (item) => item.replyId === reply.replyId,
              );
              if (replyIndex !== -1) {
                // 找到了嵌套回复
                if (res.data === true) {
                  this.$set(parentComment.reply[replyIndex], "isUp", true);
                  this.$set(
                    parentComment.reply[replyIndex],
                    "upCount",
                    (reply.upCount || 0) + 1,
                  );
                } else {
                  this.$set(parentComment.reply[replyIndex], "isUp", false);
                  this.$set(
                    parentComment.reply[replyIndex],
                    "upCount",
                    Math.max(0, (reply.upCount || 1) - 1),
                  );
                }
                found = true;
                break;
              }
            }
          }

          if (!found) {
            console.warn("无法找到要更新的评论:", reply.replyId);
          }
        }

        // 强制刷新一次
        this.$forceUpdate();
      });
    },

    goCard(info) {
      if (info.authorId == this.userId) {
        switch (uni.getSystemInfoSync().platform) {
          case "android":
            let ddd = {
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/my?authorId=${info.authorId}&userId=${this.userId}&token=${uni.getStorageSync(
                "token",
              )}`,
            };
            let d = JSON.stringify(ddd);
            console.log(d, "都是对的");
            window.AndroidBridge.myHomepage(d);
            console.log("运行Android上");
            break;
          case "ios":
            window.webkit.messageHandlers.myHomepage.postMessage({
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/my?authorId=${info.authorId}&userId=${this.userId}&token=${uni.getStorageSync("token")}`,
            });
            break;
          default:
            console.log("运行在开发者工具上");
            break;
        }
      } else {
        console.log(
          `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/card/card?authorId=${info.authorId}&userId=${this.userId}&accessToken=${uni.getStorageSync("loginInfo").accessToken}`,
        );
        switch (uni.getSystemInfoSync().platform) {
          case "android":
            let ddd = {
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/card/card?authorId=${info.authorId}&userId=${this.userId}&accessToken=${uni.getStorageSync("loginInfo").accessToken}`,
            };
            let d = JSON.stringify(ddd);
            console.log(d, "都是对的");
            window.AndroidBridge.pushNewWebVC(d);
            console.log("运行Android上");
            break;
          case "ios":
            window.webkit.messageHandlers.pushNewWebVC.postMessage({
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/card/card?authorId=${info.authorId}&userId=${this.userId}&accessToken=${uni.getStorageSync("loginInfo").accessToken}`,
            });
            break;
          default:
            console.log("运行在开发者工具上");
            break;
        }
      }
    },

    // 打赏相关方法
    rewardOperate() {
      console.log("打赏操作");
      this.isRewardPopupVisible = true;
      this.getGifts();
    },
    closePopup() {
      this.isRewardPopupVisible = false;
      this.isPayPopupVisible = false;
    },
    getGifts() {
      uni.app.post(
        "/blog/reward/list",
        {
          userId: uni.getStorageSync("userId"),
          limit: 100,
          offset: 1,
        },
        "",
        "",
        (res) => {
          this.giftsList = res.data.rows;
        },
      );
    },
    openPayPopup(item) {
      console.log("选择礼物:", item);
      this.orderItem = item;
      this.isPayPopupVisible = true;
    },
    closePayPopup() {
      this.isPayPopupVisible = false;
    },
    onPayMethodConfirm(method) {
      this.selectedPayMethod = method.value;
      this.isPayPopupVisible = false;
      uni.app.post(
        "/blog/order/consumptionPay",
        {
          userId: uni.getStorageSync("userId"),
          noteId: this.video.noteId,
          payWay: this.selectedPayMethod,
          id: this.orderItem.id,
          tradeNumber: 1,
        },
        "",
        "",
        (res) => {
          if (res.code == 2000) {
            console.log("支付订单:", res);
            uni.app.msg(res.message);
            setTimeout(() => {
              switch (this.selectedPayMethod) {
                case "1":
                  this.payNow(res.data);
                  break;
                case "2":
                  this.payNow(res.data);
                  break;
                case "4":
                  uni.navigateTo({
                    url: `/pages/hotspot/orderDetail?orderNo=${res.data.orderNo}`,
                  });
                  break;
              }
            }, 2000);
          }
        },
      );
    },
    payNow(data) {
      let ddd = {
        ...data,
        jumpUrl: "",
        paySource: "reward",
      };
      console.log("支付数据:", ddd);
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let d = JSON.stringify(ddd);
          console.log(d, "Android支付数据");
          window.AndroidBridge.aliPayForOrderStr(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.aliPayForOrderStr.postMessage(ddd);
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },

    formatDate(date) {
      return uni.app.formatDate(date);
    },

    handleTimeUpdate(e) {
      if (this.isSeeking) return;
      if (e.detail.duration > 0 && this.currentVideoDuration === 0) {
        this.currentVideoDuration = e.detail.duration;
      }
      this.currentVideoProgress = e.detail.currentTime;
    },

    handleSliderChanging() {
      this.isSeeking = true;
    },

    handleSliderChange(e) {
      const seekTime = e.detail.value;
      if (this.videoContext) {
        this.videoContext.seek(seekTime);
        this.currentVideoProgress = seekTime;
      }
      // 短暂延迟后将isSeeking设为false，防止timeupdate事件立即覆盖滑块值
      setTimeout(() => {
        this.isSeeking = false;
      }, 100);
    },

    formatTime(seconds) {
      if (isNaN(seconds) || seconds < 0) {
        return "00:00";
      }
      const min = Math.floor(seconds / 60);
      const sec = Math.floor(seconds % 60);
      return `${min < 10 ? "0" : ""}${min}:${sec < 10 ? "0" : ""}${sec}`;
    },

    // 分享功能
    share() {
      console.log("分享视频", this.video);

      // 检查数据是否已加载
      if (!this.video || !this.video.noteId) {
        console.log("视频数据未加载完成，无法分享");
        uni.showToast({
          title: "数据加载中，请稍后再试",
          icon: "none",
        });
        return;
      }
      let ddd = {
        id: this.video.noteId,
        title: this.video.noteTitle,
        detail: this.video.noteContent,
        imgUrl: this.video.firstPicture,
        type: 2,
        url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/videoDetail/videoDetail?noteId=${this.video.noteId}`,
      };
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let d = JSON.stringify(ddd);
          window.AndroidBridge.shareEvent(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.shareEvent.postMessage(ddd);
          console.log("ios");
          break;
        default:
          console.log("运行在开发者工具上");
          uni.showToast({
            title: "开发环境暂不支持分享",
            icon: "none",
          });
          break;
      }
    },
  },
};
</script>

<style>
.content,
.video-container {
  width: 100%;
  height: 100vh;
  background-color: #000;
}

.video {
  width: 100%;
  height: 100%;
}

.video-container {
  position: relative;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
  font-size: 80px;
  color: rgba(255, 255, 255, 0.6);
}

.right-actions {
  position: absolute;
  right: 10px;
  bottom: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
  z-index: 10;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.avatar-container {
  position: relative;
  margin-bottom: 20rpx;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px solid #fff;
}

.icon {
  width: 35px;
  height: 35px;
}

.action-text {
  font-size: 14px;
  margin-top: 5px;
}

.bottom-info {
  position: absolute;
  bottom: 90px;
  left: 15px;
  color: #fff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.author {
  font-size: 18px;
  font-weight: bold;
}

.video-description {
  display: block;
  margin-top: 8px;
  max-width: 85%;
  font-size: 15px;
  line-height: 1.4;
}

.video-title {
  font-weight: 600;
  margin-right: 4px;
}

.video-content {
  /* Resetting styles for inline flow with title */
  display: inline;
  margin-top: 0;
  max-width: none;
  font-size: inherit;
}

.video-time {
  display: block;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.75);
  margin-top: 8px;
}

.progress-bar-container {
  position: absolute;
  bottom: 60px;
  left: 15px;
  right: 15px;
  display: flex;
  align-items: center;
  z-index: 11;
}

.progress-slider {
  flex: 1;
  margin: 0 10px;
}

/* 声音控制按钮样式 */
.sound-control {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 5px;
}

.sound-icon {
  width: 24px;
  height: 24px;
}

.time-display {
  color: #fff;
  font-size: 12px;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.6);
  width: 90px;
  text-align: right;
}

.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.loading-text {
  color: #fff;
  font-size: 16px;
}

.no-more-videos {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.no-more-icon {
  font-size: 50px;
  margin-bottom: 10px;
}

.no-more-text {
  color: #fff;
  font-size: 16px;
}

/* 收藏夹弹窗样式 */
.list {
  background: #fff;
  width: 600rpx;
  height: 600rpx;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.list .tit {
  text-align: center;
  line-height: 100rpx;
  font-weight: 500;
  font-size: 32rpx;
  color: #333;
  border-bottom: 1rpx solid #f0f0f0;
}

.list .list-msg {
  line-height: 88rpx;
  border-bottom: 1rpx solid #f5f5f5;
  padding: 0 32rpx;
  font-size: 30rpx;
  color: #333;
  transition: background-color 0.2s ease;
}

.list .list-msg:last-child {
  border-bottom: none;
}

.list .list-msg:active {
  background-color: #f8f8f8;
}

.scroll-Y {
  padding: 0 0 20rpx 0;
}

.scroll-Y {
  height: 460rpx;
}

/* 右上角分享按钮样式 */
.top-right-share {
  position: absolute;
  top: 40rpx;
  right: 10rpx;
  z-index: 20;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
}

.share-icon {
  width: 40rpx;
  height: 40rpx;
}

/* 关注按钮样式 */
.follow-btn {
  position: absolute;
  bottom: -5px;
  right: -5px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background-color: #d9f700;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #fff;
  z-index: 10;
}

.follow-btn-img {
  position: absolute;
  bottom: -5px;
  right: -5px;
  width: 22px;
  height: 22px;
  z-index: 10;
}

/* 关注按钮样式 - 居中在头像下方 */
.follow-btn-center {
  position: absolute;
  bottom: -25rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: #ff6b6b;
  border: 4rpx solid white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.follow-btn-img-center {
  width: 30rpx;
  height: 30rpx;
}

/* 打赏弹窗样式 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.popup {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 600rpx;
  background-color: #fff;
  z-index: 1001;
  border-radius: 24rpx 24rpx 0rpx 0rpx;
}

.popup-content {
  padding: 14px 28rpx;
}

.popupTop {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.popupBtn {
  margin: 0 auto;
  width: 96rpx;
  height: 8rpx;
  background: #f2f2f2;
  border-radius: 8rpx 8rpx 8rpx 8rpx;
}

.popupText {
  margin: 32rpx auto;
  font-weight: bold;
  font-size: 30rpx;
  color: #303030;
  text-align: center;
}

.popupContent {
  display: flex;
}

.popupContentItem {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 32rpx;
}

.popupContentItem image {
  width: 210rpx;
  height: 210rpx;
}

.popupContentItem text {
  margin-top: 16rpx;
  font-weight: 400;
  font-size: 28rpx;
  color: #303030;
}

.follow-icon {
  font-size: 16px;
  color: #303030;
  font-weight: bold;
}

.followed-icon {
  font-size: 14px;
  color: #303030;
  font-weight: bold;
}

/* 关注成功提示样式 */
.success-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.success-popup {
  background-color: #fff;
  padding: 30rpx 60rpx;
  border-radius: 15rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: bold;
  color: #303030;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
</style>
